from typing import Union

from fastapi import APIRouter, HTTPException

from core.exception.exceptions import CustomerException, BusinessException
from core.utils.json_result import JsonResult

ex_router = APIRouter(prefix="/exception", tags=["异常与自定义异常"])


# 官网地址: https://fastapi.tiangolo.com/zh/tutorial/handling-errors/

@ex_router.get("/")
async def index(item_id: Union[str, None] = None):
    if item_id is None:
        body: dict = {
            "msg": "item_id is null"}
        # 当抛出 HttpException时，detail的数据会作为response body返回，detail可以是 str, dict,list等数据结构
        raise HTTPException(status_code=404, detail=body)
    # 这里可以直接返回JsonResult，类上有标识了  dataclass 注解，不需要使用 asdict() 方法来转换了
    return JsonResult.success(message="index")


@ex_router.get("/customexception")
async def custom_exception(item_id: Union[str, None] = None):
    if item_id is None:
        # 自定义异常
        raise CustomerException(message="CustomerException item_id is null")
    return JsonResult.success(message="custom_exception success")


@ex_router.get("/businessexception")
async def business_exception(item_id: Union[str, None] = None):
    if item_id is None:
        # 自定义异常
        raise BusinessException(
            json_result=JsonResult.fail(message="BusinessException item_id is null"))
    return JsonResult.success(message="Hello World", data=[{"id": 12, "name": '张三'}])
